﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using HRM.Properties;


namespace HRM
{
    public partial class FrmOfferedList : FormBase
    {
        readonly BranchClient _wcfBranch;
        readonly DepartmentClient _wcfDepartment;
        readonly PensionerClient _wcfPensioner;
        readonly int _pageSize = UIParamater.pageSize;
        int _currPage;
        int _itemCount;
        int _totalPage;
        int _pensionerId;
        int _departmentId;
        int _branchId;
        int _month = DateTime.Now.Month;
        int _year = DateTime.Now.Year;
        bool _isFirstLoad = true;
        public FrmOfferedList()
        {
            InitializeComponent();
            LoadLanguage();
            _wcfBranch = Service.Branch();
            _wcfDepartment = Service.Department();
            _wcfPensioner = Service.Pensioner();
            listRole = UIParamater.Quyen_DeNghiTroCap;
            if (!listRole.Update)
            {
                btnEdit.Image = Resources.app;
                btnEdit.Tag = "xem";
            }
            UISetting.LoadMonths(ref cbMonth);
            if (cbMonth.ComboBox != null)
                cbMonth.ComboBox.SelectedValue = Convert.ToUInt32(DateTime.Now.Month);
            UISetting.LoadYears(ref cbYear);

            UISetting.LoadTreeView3(ref tvBranch);
            btnNew.Enabled = listRole.Create;
            btnEdit.Enabled = listRole.Update;
            btnDel.Enabled = listRole.Delete;

            dtgData.MouseDown += dgvList_MouseDown;
            dtgData.CellDoubleClick += dgvList_CellDoubleClick;
            pager.AllowChangePageSize = true;
        }


        public override void Show_Form()
        {
            Show();
        }

        protected override void Init_Control()
        {
            InitGrid();

        }
        /// <summary>
        /// Định nghĩa các cột cho DataGridView
        /// </summary>
        private void InitGrid()
        {
            dtgData.Columns.Clear();
            var arrColumn = new List<DataGridViewColumn>
                                {
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Pensioner_ID","Pensioner_ID", 0,""),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Pensioner_DepartmentID","Pensioner_DepartmentID", 0,""),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Số sổ BHXH","Pensioner_SiBookNo", 150,"",true),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>(GetMsb("hovaten"),"FullName", 150,"",true),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>(GetMsb("denghi"),"Grant_Name", 150,"",true),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>(GetMsb("noidung"),"SubGrant_Name", 150,"",true),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Số tiền trợ cấp","Pensioner_Amount", 120,Globals.CS_DISPLAY_NUMBER_FORMAT,true),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Ngày nhập","Pensioner_Date", 120,Globals.CS_DISPLAY_DATE_FORMAT,true),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Tình trạng","Pensioner_StateParturition", 120,"",true),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>(GetMsb("ghichu"),"Pensioner_Description",0,""),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("lương bảo hiểm","Pensioner_Salary", 0,""),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Thời gian đóng BHXH","Pensioner_InsuranceTime", 0,""),
                                };

            FormGlobals.Grid_Init(dtgData, arrColumn, "", 1);
        }

        private string GetMsb(string str)
        {
            return UpdateUI.GetString(str);
        }

        void LoadLanguage()
        {
            TabText = Text = GetMsb(Tag.ToString());
            UpdateUI.Load_ToolStrip(ref toolStrip1);

        }

        private void BindData()
        {
            _month = Convert.ToInt32(cbMonth.Text);
            int temptYear;
            if (Int32.TryParse(cbYear.Text, out temptYear))
                _year = temptYear;
            var ds = _wcfPensioner.Pensioner_GetList(out _itemCount, pager.PageIndex, pager.PageSize, _branchId, _departmentId, _month, _year);
            dtgData.DataSource = ds.Tables[0];
            pager.TotalRow = _itemCount;

        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (!listRole.Create)
            {
                MessageBox.Show(GetMsb("khongcoquyenthemmoi"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            Form f = new frmOfferedInfo(0, listRole, 0);
            if (f.ShowDialog(this) == DialogResult.OK)
            {
                pager.PageIndex = 0;
                BindData();
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dtgData.SelectedCells.Count <= 0) return;
            if (listRole.Update || listRole.View)
            {
                if (dtgData.CurrentRow != null)
                    _pensionerId = Convert.ToInt32(dtgData.CurrentRow.Cells["Pensioner_ID"].Value);
                Form f = new frmOfferedInfo(_pensionerId, listRole, 0);
                if (f.ShowDialog(this) == DialogResult.OK)
                {
                    pager.PageIndex = 0;
                    BindData();
                }
            }
            else
                MessageBox.Show(GetMsb("khongcoquyenxem"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (dtgData.SelectedCells.Count <= 0) return;
            if (!listRole.Delete)
            {
                MessageBox.Show(GetMsb("khongcoquyenxoa"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (dtgData.CurrentRow != null)
                _pensionerId = Convert.ToInt32(dtgData.CurrentRow.Cells["Pensioner_ID"].Value);
            if (
                MessageBox.Show(GetMsb("bancochacchanxoa"), UIParamater.TitleProject,
                                MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return;
            if (_wcfPensioner.Pensioner_Delete(_pensionerId))
            {
                Program.taskbarNotifier.Show(UIParamater.TitleProject, GetMsb("xoathanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                pager.PageIndex = 0;
                BindData();
            }
            else
            {
                MessageBox.Show(GetMsb("xoakhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
                btnEdit.PerformClick();
        }

        private void frmOfferedList_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Escape:
                    Dispose();
                    Close();
                    break;
                case Keys.F2:
                    btnNew_Click(null, null);
                    break;
                case Keys.F3:
                    btnEdit_Click(null, null);
                    break;
                case Keys.Delete:
                    btnDel_Click(null, null);
                    break;
            }
        }

        private void btnNewPopUp_Click(object sender, EventArgs e)
        {
            btnNew.PerformClick();
        }

        private void btnEditPopUp_Click(object sender, EventArgs e)
        {
            btnEdit.PerformClick();
        }

        private void btnDelPopUp_Click(object sender, EventArgs e)
        {
            btnDel.PerformClick();
        }



        private void tvBranch_AfterSelect(object sender, TreeViewEventArgs e)
        {
            switch (e.Node.Level)
            {
                case 0:
                    if (Program.isAdmin || Program.isViewAll)
                    {
                        _branchId = 0;
                        _departmentId = 0;
                    }
                    else
                        _branchId = Program.intBranchID;

                    pager.PageIndex = 0;
                    BindData();
                    break;
                case 1:
                    _branchId = Convert.ToInt32(e.Node.Tag);
                    _departmentId = 0;
                    pager.PageIndex = 0;
                    BindData();
                    break;
                default:
                    if (e.Node.Level >= 2)
                    {
                        _departmentId = Convert.ToInt32(e.Node.Tag);
                        _branchId = Convert.ToInt32(e.Node.Parent.Tag);
                        pager.PageIndex = 0;
                        BindData();

                    }
                    break;
            }
        }

        private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_isFirstLoad) return;
            pager.PageIndex = 0;
            BindData();
        }

        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_isFirstLoad) return;
            pager.PageIndex = 0;
            BindData();
        }

        private void frmOfferedList_Activated(object sender, EventArgs e)
        {
            LoadLanguage();
            if (dtgData.Columns.Count > 0)
            {
                var dataGridViewColumn = dtgData.Columns["FullName"];
                if (dataGridViewColumn != null)
                    dataGridViewColumn.HeaderText = GetMsb("hovaten");
                dataGridViewColumn = dtgData.Columns["Grant_Name"];
                if (dataGridViewColumn != null)
                    dataGridViewColumn.HeaderText = GetMsb("denghi");
                dataGridViewColumn = dtgData.Columns["SubGrant_Name"];
                if (dataGridViewColumn != null)
                    dataGridViewColumn.HeaderText = GetMsb("noidung");
                dataGridViewColumn = dtgData.Columns["Pensioner_Amount"];
                if (dataGridViewColumn != null)
                    dataGridViewColumn.HeaderText = GetMsb("sotien");
                dataGridViewColumn = dtgData.Columns["Pensioner_Date"];
                if (dataGridViewColumn != null)
                    dataGridViewColumn.HeaderText = GetMsb("ngay");
                dataGridViewColumn = dtgData.Columns["Pensioner_Description"];
                if (dataGridViewColumn != null)
                    dataGridViewColumn.HeaderText = GetMsb("ghichu");
            }
        }

        private void frmOfferedList_FormClosing(object sender, FormClosingEventArgs e)
        {
            _wcfBranch.Close();
            _wcfDepartment.Close();
            _wcfPensioner.Close();
        }

        private void dgvList_MouseDown(object sender, MouseEventArgs e)
        {
            if (dtgData.SelectedRows.Count > 0)
            {
                if (e.Button == MouseButtons.Right)
                {
                    mnuPopUp.Enabled = true;
                    btnNewPopUp.Enabled = true;
                    btnEditPopUp.Enabled = true;
                    btnDelPopUp.Enabled = true;
                }
            }
        }

        private void frmOfferedList_Load(object sender, EventArgs e)
        {
            _isFirstLoad = false;
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            frmTime fTime = new frmTime(1);
            if (fTime.ShowDialog(this) == DialogResult.OK)
            {
                if (listRole.View)
                {
                    if (cbMonth.ComboBox != null)
                    {
                        if (cbYear.ComboBox != null)
                        {
                            var f = new frmPreviewReport("denghihuongtrocap", new[] { "Đề nghị hưởng trợ cấp", cbMonth.ComboBox.SelectedValue.ToString(), cbYear.ComboBox.SelectedValue.ToString(),fTime.FromDate.ToString(),fTime.ToDate.ToString() });
                            f.ShowDialog();
                        }
                    }
                }
                else
                    MessageBox.Show(HrmResources.YOU_CAN_NOT_VIEW, UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void pager_PageIndex_Changed(int pageIndex)
        {
            BindData();
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            pager.PageIndex = 0;
            BindData();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            splitContainer1.Panel1Collapsed = !splitContainer1.Panel1Collapsed;
            toolStripButton1.Image = splitContainer1.Panel1Collapsed ? Properties.Resources.right16 : Properties.Resources.left16;
        }
    }
}